package com.llxwz.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.llxwz.dao.UserMapper;
import com.llxwz.entity.LoginTicket;
import com.llxwz.entity.User;
import com.llxwz.util.CommunityConstant;
import com.llxwz.util.CommunityUtil;
import com.llxwz.util.MailUtil;
import com.llxwz.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;



@Service
public class UserService implements CommunityConstant {
    @Autowired
    private UserMapper userMapper;

    /*@Autowired
    private LoginTicketDao loginTicketDao;*/

    @Autowired
    private MailUtil mailUtil;

    @Autowired
    private TemplateEngine templateEngine;

    //跳转的网页地址
    @Value("${community.path.domain}")
    private String domain;
    //项目名
    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private RedisTemplate redisTemplate;

    public User findById(int id){
        //return userDao.selectById(id);
        User user = getCache(id);
        if (user == null) {
            user = initCache(id);
        }
        return user;
    }

    //注册账号
    public Map<String, Object> register(User user) {
        Map<String,Object> map = new HashMap<>();

        //空值处理
        if(user==null){
            throw new IllegalArgumentException("user不能为空!");
        }
        //username不能空
        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg","用户名不能为空");
            return map;
        }
        //密码不能空
        if(StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg","密码不能为空");
            return map;
        }
        //邮箱不能空
        if(StringUtils.isBlank(user.getEmail())){
            map.put("emailMsg","邮箱不能为空");
            return map;
        }


        //验证账号
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("username",user.getUsername());
        User u = userMapper.selectOne(wrapper);
        //用户已存在
        if(u!=null){
            map.put("usernameMsg","用户已存在");
            return map;
        }

        //邮箱唯一
        QueryWrapper wrapper1 = new QueryWrapper();
        wrapper1.eq("email",user.getEmail());
        u = userMapper.selectOne(wrapper1);
        if(u!=null){
            map.put("emailMsg","邮箱已被注册");
            return map;
        }
        
        //salt用于加密密码
        user.setSalt(CommunityUtil.generateUUID().substring(0,5));
        //在密码后加入salt,在加密
        user.setPassword(CommunityUtil.md5(user.getPassword()+user.getSalt()));
        //设置为普通用户
        user.setType(0);
        //设置为未激活
        user.setStatus(0);
        //设置激活码
        user.setActivationCode(CommunityUtil.generateUUID());
        //设置随机头像
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        //设置创建时间
        user.setCreateTime(new Date());
        //仅仅插入用户信息，用户账号并未激活
        userMapper.insert(user);

        //用户在点击注册按钮后，系统在后端直接发送激活邮件
        //mybatis自增长主键自动回填
        /*u = userDao.selectByName(user.getUsername());*/

        //向要发送的html的页面传入的参数
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        //http://localhost:8088/forum/activation/id/激活码
        String url = domain + contextPath + "/activation/" + user.getId() + '/' +user.getActivationCode();
        context.setVariable("url",url);
        //指定要发送的html文件
        String content = templateEngine.process("mail/activation",context);
        //发送邮件
        mailUtil.sendMail(user.getEmail(),"数字学院激活邮件",content);

        return map;
    }

    //激活账号
    public int activation(int userId, String code) {
        User user = userMapper.selectById(userId);
        if(user.getStatus()==1){//用户已激活
            return ACTIVATION_REPEAT;
        }else if(user.getActivationCode().equals(code)){
            //将用户设置为已激活
            //user.setStatus(1);
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("id",user.getId());
            updateWrapper.set("status",1);
            userMapper.update(null,updateWrapper);

            clearCache(userId);

            return ACTIVATION_SUCCESS;
        }else{
            //激活码不正确
            return ACTIVATION_FAILURE;
        }
    }


    //登录账号
    public Map<String, Object> login(String username,String password,int expiredSeconds){
        Map<String,Object> map = new HashMap<>();

        //参数不能为空
        if(StringUtils.isBlank(username)){
            map.put("usernameMsg","用户名不能为空");
            return map;
        }
        if (StringUtils.isBlank(password)){
            map.put("passwordMsg","密码不能为空");
            return map;
        }

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User u = userMapper.selectOne(wrapper);

        if(u==null){
            map.put("usernameMsg","没有注册该用户");
            return map;
        }
        if (u.getStatus()==0){
            map.put("usernameMsg","该用户未激活");
            return map;
        }
        if (u.getStatus()==2){
            map.put("usernameMsg","该用户已被封号");
            return map;
        }

        //密码比较
        password = CommunityUtil.md5(password+u.getSalt());
        if(!u.getPassword().equals(password)){
            map.put("passwordMsg","密码错误");
            return map;
        }

        //以上通过验证，以下生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(u.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        //设置过期时间为现在时间的后 记住我*1000s
        loginTicket.setExpired(new Date(System.currentTimeMillis()+expiredSeconds*1000));

        //loginTicketDao.insertLoginTicket(loginTicket);(已改进)

        //将loginTicket对象转换成json对象
        String redisKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(redisKey,loginTicket);

        map.put("ticket", loginTicket.getTicket());
        return map;

    }

    //获取邮箱验证码
    public Map<String,Object> sendMail(String email){
        Map<String,Object> map = new HashMap<>();

        //参数不能为空
        if(StringUtils.isBlank(email)){
            map.put("emailMsg","邮箱不能为空");
            return map;
        }

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email",email);
        User u = userMapper.selectOne(wrapper);

        if(u==null){
            map.put("emailMsg","没有用该邮箱注册用户");
            return map;
        }
        if (u.getStatus()==0){
            map.put("emailMsg","该用户未激活");
            return map;
        }
        if (u.getStatus()==2){
            map.put("emailMsg","该用户已被封号");
            return map;
        }

        //向要发送的html的页面传入的参数
        Context context = new Context();
        context.setVariable("email", email);
        //生成验证码
        String mailCode = String.valueOf(CommunityUtil.generateValidateCode(6));
        context.setVariable("code",mailCode);
        //指定要发送的html文件
        String content = templateEngine.process("mail/getCode",context);
        //发送邮件
        mailUtil.sendMail(email,"数字学院验证码",content);

        map.put("mailCode",mailCode);

        return map;
    }

    //邮箱验证码登录
    public Map<String,Object> mailLogin(String email,int expiredSeconds){
        Map<String,Object> map = new HashMap<>();

        //参数不能为空
        if(StringUtils.isBlank(email)){
            map.put("mailMsg","邮箱不能为空");
            return map;
        }

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email",email);
        User u = userMapper.selectOne(wrapper);

        if(u==null){
            map.put("mailMsg","没有注册该用户");
            return map;
        }
        if (u.getStatus()==0){
            map.put("mailMsg","该用户未激活");
            return map;
        }
        if (u.getStatus()==2){
            map.put("mailMsg","该用户已被封号");
            return map;
        }


        //以上通过验证，以下生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(u.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        //设置过期时间为现在时间的后 记住我*1000s
        loginTicket.setExpired(new Date(System.currentTimeMillis()+expiredSeconds*1000));

        //将loginTicket对象转换成json对象
        String redisKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(redisKey,loginTicket);

        map.put("ticket", loginTicket.getTicket());
        return map;

    }

    //查询登录凭证表
    public LoginTicket findLoginTicketByTicket(String ticket){
        //return loginTicketDao.selectByTicket(ticket);
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(redisKey);
    }



    //退出账号
    public void loginOut(String ticket){
        //loginTicketDao.updateStatus(ticket,1);
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(redisKey,loginTicket);
    }

    //获取用户列表
    public List<User> getUsers(String username,int type,int status,int current, int limit){
        QueryWrapper wrapper = new QueryWrapper();
        if (!"null".equals(username)){
            wrapper.like("username",username);
        }
        if(status!=-1){
            wrapper.eq("status",status);
        }
        if(type!=-1){
            wrapper.eq("type",type);
        }
        Page<User> result = userMapper.selectPage(new Page<>(current,limit), wrapper);
        return result.getRecords();
    }

    //获取用户列表行数
    public int getUserCount(String username,int type,int status){
        QueryWrapper wrapper = new QueryWrapper();
        if (!"null".equals(username)){
            wrapper.like("username",username);
        }
        if(status!=-1){
            wrapper.eq("status",status);
        }
        if(type!=-1){
            wrapper.eq("type",type);
        }
        return userMapper.selectCount(wrapper);
    }

    //修改权限
    public int setType(int id,int type){
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",id);
        updateWrapper.set("type",type);

        int i = userMapper.update(null,updateWrapper);
        return i;
    }


    public int setStatus(int id,int status){
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",id);
        updateWrapper.set("status",status);

        int i = userMapper.update(null,updateWrapper);
        return i;
    }

    //更新头像
    public int changeHeader(int id, String headerUrl){
        //return userDao.updateHeader(id,headerUrl);
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",id);
        updateWrapper.set("header_url",headerUrl);

        int i = userMapper.update(null,updateWrapper);
        clearCache(id);
        return i;
    }
    //更新密码
    public int changePassword(int id, String password){
        //return userDao.updatePassword(id,password);

        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",id);
        updateWrapper.set("password",password);

        int i = userMapper.update(null,updateWrapper);
        clearCache(id);
        return i;
    }
    //更新个性签名
    public int changeSign(int id,String sign){
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",id);
        updateWrapper.set("sign",sign);

        int i = userMapper.update(null,updateWrapper);
        clearCache(id);
        return i;
    }
    //绑定手机号
    public int changePhone(int id,String phone){
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",id);
        updateWrapper.set("phone",phone);

        int i = userMapper.update(null,updateWrapper);
        clearCache(id);
        return i;
    }

    public User findUserByName(String username){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        return userMapper.selectOne(wrapper);
    }

    // 1.优先从缓存中取值
    private User getCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    // 2.取不到时初始化缓存数据
    private User initCache(int userId) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("userId",userId);
        User user = userMapper.selectById(userId);
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }

    // 3.数据变更时清除缓存数据
    private void clearCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(redisKey);
    }

    //获取用户的权限
    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        User user = this.findById(userId);

        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {

            //0普通用户 1管理员
            @Override
            public String getAuthority() {
                switch (user.getType()) {
                    case 1:
                        return AUTHORITY_ADMIN;
                    default:
                        return AUTHORITY_USER;
                }
            }
        });
        return list;
    }


}
